extends Node

signal _server_connected()
signal _server_disconnected()
signal _server_connection_failed()
signal _client_peer_connected(id: int)
signal _client_disconnected_event(id: int)
signal _client_authenticating(id: int)
signal _client_authentication_failed(id: int)

var peer : ENetMultiplayerPeer = ENetMultiplayerPeer.new()

func _ready() -> void:
	peer.create_client("127.0.0.1",25003)

func _create_multiplayer(_multiplayer : MultiplayerAPI) -> void :
	_multiplayer.auth_callback = _on_client_auth_callback
	_multiplayer.connected_to_server.connect(_on_server_connected)
	_multiplayer.server_disconnected.connect(_on_server_disconnected)
	_multiplayer.connection_failed.connect(_on_server_connection_failed)
	_multiplayer.peer_connected.connect(_on_client_peer_connected)
	_multiplayer.peer_disconnected.connect(_on_client_peer_disconnected)
	_multiplayer.peer_authenticating.connect(_on_client_authenticating)
	_multiplayer.peer_authentication_failed.connect(_on_client_authentication_failed)

func _set_multiplayer(_multiplayer : MultiplayerAPI) -> void :
	_multiplayer.multiplayer_peer = peer

#client
func _on_server_connected() :
	print("服务器连接功")
	_server_connected.emit()

#client
func _on_server_disconnected() :
	print("与服务器断开连接")
	_server_disconnected.emit()

#client
func _on_server_connection_failed() :
	print("与服务器连接失败")
	_server_connection_failed.emit()

#client
func _on_client_peer_connected(id: int) :
	print("玩家：",id,"连接")
	_client_peer_connected.emit(id)

#client
func _on_client_peer_disconnected(id: int) :
	print("玩家：",id,"断连")
	_client_disconnected_event.emit(id)

func _on_client_authenticating(id: int) :
	print(id,"申请鉴权")
	_client_authenticating.emit(id)

func _on_client_authentication_failed(id: int) :
	print(id,"鉴权失败")
	_client_authentication_failed.emit()

func _on_client_auth_callback(_id: int, _data: PackedByteArray) :
	print(_data.get_string_from_utf8())
